package com.yf.aclient.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.yf.aclient.R;
import com.yf.aclient.adapter.MyAdapter;
import com.yf.aclient.adapter.MyAdapter.ViewHolder;
import com.yf.aclient.util.DateUtil;
import com.yf.aclient.util.NumberUtil;

public class ExDialog extends ListActivity {
	private List<Map<String, Object>> mData;
	private String mDir = "/sdcard";
	private  LinearLayout  linerlayout;
	private  int  selectCount=0;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Intent intent = this.getIntent();
		Bundle b = intent.getExtras();
		setTitle(b.getString("title"));
		setContentView(R.layout.fileslist);
		//Bundle bl = intent.getExtras();
		//String title = bl.getString("explorer_title"); // 接收标题内容
		Uri uri = intent.getData(); // 接收起始目录
		mDir = uri.getPath(); // 设置起始目录
		linerlayout=(LinearLayout) findViewById(R.id.options);
		
		mData = getData(); // 向链表mData填充目录的数据
		MyAdapter adapter = new MyAdapter(this, mData);
		setListAdapter(adapter); // 设置MyAdapter类为ListView控件提供数据

		WindowManager m = getWindowManager();
		Display d = m.getDefaultDisplay();
		LayoutParams p = getWindow().getAttributes();
		p.height = (int) (d.getHeight());
		p.width = (int) (d.getWidth());
		getWindow().setAttributes(p); // 设置对话框为固定大小，不因进出目录变化
		
		Button  btOk=(Button)findViewById(R.id.bt_ok);
		Button  btCancel=(Button)findViewById(R.id.bt_cancel);
		/***
		 * 确定上传文件
		 */
		btOk.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
            	showDialog(1);
            	return;
			}
		});
		/**
		 * 取消上传
		 */
		btCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				linerlayout.setVisibility(View.INVISIBLE);
			}
		});
  
	}

	private List<Map<String, Object>> getData() { // 将目录数据填充到链表中
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		File f = new File(mDir); // 打开当前目录
		File[] files = f.listFiles(); // 获取当前目录中文件列表

		if (!mDir.startsWith("/sdcard")) { // 不充许进入/sdcard上层目录
			map = new HashMap<String, Object>(); // 加返回上层目录项
			map.put("name", "不能查看sdcard以外目录");
			map.put("fileSize", "");
			map.put("modifyDate","");
			map.put("isDirectory", true);
			map.put("img", getResources().getDrawable(R.drawable.back));
			list.add(map);
			return list;
		}
		if (files != null) { // 将目录中文件填加到列表中
			map = new HashMap<String, Object>();
			//增加返回按钮。。
					map.put("name", mDir);
					map.put("fileSize", "");
					map.put("modifyDate","");
					map.put("isSelected",false);
					map.put("isDirectory", true);
					map.put("isBack",true);
					map.put("img", getResources().getDrawable(R.drawable.back));
					list.add(map);
			for (int i = 0; i < files.length; i++) {
				map = new HashMap<String, Object>();
				map.put("name", files[i].getName());
				if (files[i].isDirectory()) {// 按不同类型显示不同图标
					map.put("img", getResources().getDrawable(R.drawable.folder));
					map.put("fileSize", "");
					map.put("modifyDate", "");
					map.put("isSelected",false);
					map.put("isDirectory", true);
				}else{
					Double size= files[i].length()/1024.0;
					Date date= new Date(files[i].lastModified());
					map.put("img", getResources().getDrawable(R.drawable.file));
					map.put("fileSize",NumberUtil.convertNumbertoString(2, size)+"KB" );
					map.put("modifyDate",DateUtil.convertDateToString(date, "yyyy-MM-dd HH:mm:ss"));
					map.put("isSelected",false);
					map.put("isDirectory", false);
				}
				map.put("path",files[i].getPath());
				map.put("isBack",false);
				list.add(map);
			}
		}
		return list;
	}

	// 响应用户点击列表项的事件
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		//Log.d("MyListView4-click", (String) mData.get(position).get("path"));
		
		if ((Boolean) mData.get(position).get("isBack")) {
			linerlayout.setVisibility(View.INVISIBLE);
			selectCount=0;
			mDir = (String) mData.get(position).get("name");
			if(mDir.equals("/sdcard"))
				return;
			int  i=mDir.lastIndexOf(File.separator);
			mDir = mDir.substring(0,i);
			mData = getData(); // 点击目录时进入子目录
			MyAdapter adapter = new MyAdapter(this, mData);
			setListAdapter(adapter);
			return;
		}
		if ((Boolean) mData.get(position).get("isDirectory")) {
			mDir = (String) mData.get(position).get("path");
			mData = getData(); // 点击目录时进入子目录
			MyAdapter adapter = new MyAdapter(this, mData);
			setListAdapter(adapter);
			return;
		}else{//选择当前行后的checkbox
			mDir = (String) mData.get(position).get("path");
			ViewHolder vHollder = (ViewHolder) v.getTag();
			// 在每次获取点击的item时将对于的checkbox状态改变，同时修改map的值。
			vHollder.checkBox.toggle();
			if(vHollder.checkBox.isChecked()){//如果是选中。
				selectCount++;
				Log.i("checked:selectCount", selectCount+"");
			}else{
				selectCount--;
				Log.i("unchecked:selectCount", selectCount+"");
			}
			if(selectCount>0){
				linerlayout.setVisibility(View.VISIBLE)	;
			}else{
				linerlayout.setVisibility(View.INVISIBLE);
			}
			MyAdapter.mData.get(position).put("isSelected", true);
		//	linerlayout.setVisibility(View.VISIBLE);
			//openOptionsMenu();
			return;
		}
	}

//	private void finishWithResult(String path) {
//		Bundle conData = new Bundle();
//		conData.putString("results", "Thanks Thanks");
//		Intent intent = new Intent(); // 以intent的方式将结果返回调用类
//		intent.putExtras(conData);
//		Uri startDir = Uri.fromFile(new File(path));
//		intent.setDataAndType(startDir,
//				"vnd.Android.cursor.dir/lysesoft.andexplorer.file");
//		setResult(RESULT_OK, intent);
//		finish();
//	}
//	
//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//    	super.onCreateOptionsMenu(menu);
//    	 //set
//        MenuInflater inflater = getMenuInflater();
//        inflater.inflate(R.menu.title_ico_upload, menu);
//    	return true;
//    }
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.confirm:
////                Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_SHORT).show();
//            {
//            	showDialog(1);
//            	return true;
//            }
//            case R.id.cancel:
//                return true;
//            default:
//                // Don't toast text when a submenu is clicked
//                if (!item.hasSubMenu()) {
//                    Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
//                    return true;
//                }
//                break;
//        }
//        
//        return false;
//    }
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 1:
			LayoutInflater factory = LayoutInflater.from(this);
			final View textEntryView = factory.inflate(R.layout.enterfilememo,
					null);
			return new AlertDialog.Builder(ExDialog.this)
			.setIcon(R.drawable.alert_dialog_icon)
			.setTitle(R.string.enter_memo)
			.setView(textEntryView)
			.setPositiveButton(R.string.confirm,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							String[] result = new String[mData.size()];
							int n=mData.size();
							for(int i=0;i<n;i++){
			            		Map map=mData.get(i);
			            		if((Boolean)map.get("isSelected")){
			            			result[i]=map.get("path").toString();
			            		}else
			            			result[i]="";
			            	}
							Intent intent = new Intent("fromSelectPicActivity");
							intent.putExtra("data", result);
							EditText editText=(EditText)textEntryView.findViewById(R.id.fileMemo);
							 intent.putExtra("memo", editText.getText().toString());
							setResult(RESULT_OK, intent);
//							Toast.makeText(getBaseContext(), "图片选择完毕", Toast.LENGTH_LONG)
//									.show();
							finish();
							/* User clicked Yes so do some stuff */
						}
					})
			.setNegativeButton(R.string.cancel,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {

							/* User clicked No so do some stuff */
						}
					}).create();
			default:
				break;
			
		}

		return null;
	}
}
